package models

import (
	"github.com/beego/beego/v2/adapter/orm"
)

type Customers struct {
	CustomerID            int    `orm:"column(customer_ID)"`
	CustomerName          string `orm:"column(customer_name)"`
	ServiceTimes          int    `orm:"column(service_times)"`
	LastServiceFinishTime string `orm:"column(last_service_finish_time)"`
	CompanyName           string `orm:"column(company_name)"`
	CustomerEmail         string `orm:"column(customer_email)"`
	CustomerPhone         string `orm:"column(customer_phone)"`
	CustomerStatus        int    `orm:"column(customer_status)"`
}

func init() {
	orm.RegisterModel(new(Customers))
}

type CustomerSubmitModel struct {
	CustomerName    string `json:"customerName" orm:"column(customer_name)"`
	CustomerCompany string `json:"customerCompany" orm:"company_name"`
	Email           string `json:"email" orm:"column(customer_email)"`
	PhoneNumber     string `json:"phoneNumber" orm:"column(customer_phone)"`
}

// AddCustomer 添加客户
func AddCustomer(submit CustomerSubmitModel, contactID int) error {
	o := orm.NewOrm()
	err := o.Begin()
	result, err := o.Raw("insert into customers (customer_name, company_name, customer_email, customer_phone,customer_come_date) values (?,?,?,?,now())", submit.CustomerName, submit.CustomerCompany, submit.Email, submit.PhoneNumber).Exec()
	_, err = o.Raw("update latent_customer set latent_status = 1 where name = ? and company = ?", submit.CustomerName, submit.CustomerCompany).Exec()
	id, _ := result.LastInsertId()
	_, err = o.Raw("insert into contact_customer_mid (customer_ID, contact_ID) values (?,?)", id, contactID).Exec()
	if err != nil {
		err = o.Rollback()
		return err
	} else {
		err = o.Commit()
		return nil
	}
}
